<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="js/vue.js"></script>
	</head>
	<style type="text/css">
		* {
			margin: 0;
			padding: 0;
			box-sizing: border-box;
			list-style: none;
		}

		ul {
			width: 310px;
			background-color: #421c0F;
			display: flex;
			flex-wrap: wrap;
			margin: 30px auto;
			border: 5px solid #421C0F;
			border-radius: 5px;
		}

		li {
			width: 100px;
			height: 100px;
			background-color: #E4B77C;
			border: 1px solid #421C0F;
			text-align: center;
			line-height: 100px;
			font-weight: bold;

		}

		.number0 {
			/* 空白格样式 */
			opacity: 0;
		}

		button {
			padding: 10px 20px;
			background: #421C0F;
			border-color: #421C0F;
			color: #fff;
			border-radius: 5px;
			display: block;
			margin: 10px auto;
		}

		.list-move {
			transition: .5s;
		}
	</style>
	<body>
		<div id="app">
			<h1 align="center">{{m>10?m:'0'+m}}:{{s>10?s:'0'+s}}</h1>
			<transition-group tag='ul' name="list">
				<li :class="'number'+item" v-for='(item,index) in list' @click="move(index)" :key='item'>
					{{item>0?item:''}}/{{index}}
				</li>
			</transition-group>
			<button @click="start()">开始游戏</button>
		</div>
		<script type="text/javascript">
			Vue.createApp({
				data() {
					return {
						list: [1, 2, 3, 4, 5, 6, 7, 8, 0],
						mark: [1, 2, 3, 4, 5, 6, 7, 8, 0],
						m: 0,
						s: 0,
						timer: null
					}
				},
				methods: {
					setTime() {
						timer = setInterval(() => {
							this.s++
							if (this.s >= 60) {
								this.m++
								this.s = 0
							}
						}, 1000)
					},
					isEnd() {
						for (let i = 0; i < 9; i++) {
							if (this.list[i] != this.mark[i]) {
								return false
							}
						}
						clearInterval(timer)
						return true //游戏成功
					},
					start() {
						this.list.sort(() => Math.random() - 0.5)
						this.s = 0
						this.m = 0
						this.setTime()
					},
					move(i) {

						var neb = [i - 3, i + 3, i - 1, i + 1] //上下左右
						if (parseInt(neb[2] / 3) != parseInt(i / 3)) {
							neb[2] = -1 //判断左边和i是不是同一行
						}
						if (parseInt(neb[3] / 3) != parseInt(i / 3)) {
							neb[3] = -1 //判断有边和i是不是同一行
						}
						for (let j = 0; j < 4; j++) {
							if (neb[j] >= 0 && this.list[neb[j]] == 0) {
								let next = neb[j]
								this.list[next] = this.list[i] //将方块推到空白格
								this.list[i] = 0 //新空白格
								break
							}
						}
						if (this.isEnd()) {
							setTimeout(() => {
								alert('挑战成功！')
							}, 10);
						}
					}
				}

			}).mount('#app')
		</script>
	</body>
</html>
